<template>
  <div>
    <c-section title="申请人信息">
      <c-list :column="3">
        <c-list-item type="input" label="申请人" :value="detail.applicantName" />
        <c-list-item type="input" label="申请人电话" :value="detail.phone" />
        <c-list-item type="input" label="申请时间" :value="detail.applicantTime" />
        <c-list-item type="input" :span="3" label="申请人部门" :value="handlerOrg(detail.orgDtos)" />
      </c-list>
    </c-section>
    <c-section title="门店信息">
      <c-list :column="3">
        <c-list-item type="input" label="所属办事处" :value="detail.officeName" />
        <c-list-item type="input" label="办事处性质" :value="detail.officeNature" />
        <c-list-item type="input" label="商家类别" dict-type-code="BIZMAN_TYPE" :value="detail.bizmanType" />
        <c-list-item type="input" label="经销商姓名" :value="detail.customerName " />
        <c-list-item type="input" label="经销商电话" :value="detail.customerPhone" />
        <c-list-item type="input" label="客户编码" :value="detail.clientCode" />
        <c-list-item type="input" label="客户名称" :value="detail.clientName" />
        <c-list-item type="input" label="门店编码" :value="detail.shopCode" />
        <c-list-item type="input" label="门店名称" :value="detail.shopName" />
        <c-list-item type="input" label="门店档案面积" suffix="㎡" :value="detail.shopWholeTotalArea" />
        <c-list-item type="input" label="城市级别" dict-type-code="CITY_LEVEL" :value="detail.shopCityLevel" />
        <c-list-item type="input" label="门店类型" dict-type-code="SHOP_TYPE" :value="detail.shopType" />
        <c-list-item type="input" label="门店市场层级" dict-type-code="MARKET_LEVEL" :value="detail.shopMarketLevel" />
        <c-list-item type="input" label="门店营业状态" dict-type-code="SHOP_BIZ_STATE" :value="detail.businessStatus" />
        <c-list-item type="input" label="业务类型" dict-type-code="BIZ_TYPE" :value="detail.shopBizType" />
        <c-list-item type="input" label="门店详细地址" :value="detail.shopAddress" :span="2" />
      </c-list>
    </c-section>
    <c-section title="门店建设信息">
      <c-list :column="3">
        <c-list-item type="input" label="门店建设项目号" :value="detail.constCode" />
        <c-list-item type="input" label="报图类型" dict-type-code="MARKET_TYPE" :value="detail.marketType" />
        <c-list-item type="input" label="门店建设类型" dict-type-code="CONST_TYPE" :value="detail.constType" />
        <c-list-item type="input" label="门店建设范围" dict-type-code="DECORATION_RANGE" :value="detail.decorationRange" />
        <c-list-item type="input" label="装修形式" dict-type-code="DECORATION_FORM" :value="detail.decorationFormCal || detail.decorationForm" />
      </c-list>
    </c-section>
    <c-section title="装修信息">
      <c-list :column="3">
        <c-list-item type="input" label="装修任务号" :value="detail.decorationTaskCode" />
        <c-list-item type="input" label="装修进度" dict-type-code="DECORATION_SCHEDULE" :value="detail.schedule" />
        <c-list-item type="input" label="装修步骤" dict-type-code="SHOP_DECORATION_STEPS" :value="detail.steps" />
        <c-list-item type="input" label="预计进场装修时间" :value="detail.expectDecorationTime" />
        <c-list-item type="input" label="预计开业时间" :value="detail.expectOpenTime" />
        <c-list-item type="input" label="装修状态" dict-type-code="SHOP_DECORATION_STATE" :value="detail.state" />
        <c-list-item type="input" label="本次装修卖场面积" suffix="㎡" :value="detail.shopDecorationTotalArea" />
        <c-list-item type="input" label="本次装修门头面积" suffix="㎡" :value="detail.dheadDecorationTotalArea" />
        <c-list-item type="input" label="装修申请说明" :value="detail.expectDesc" :span="3" />
      </c-list>
    </c-section>

    <div class="qup-title-box"><span class="border" /><span>委派信息</span></div>
    <search-form
      style="width:600px"
      :search-config="searchConfig"
      :label-width="150"
      @clear="clearSearch"
      @search="handleSearch"
    />

    <table-box
      ref="refTable"
      :table-config="tableConfig"
      :other-filters="otherFilters"
      table-row-key="id"
      no-request
      show-index
      :table-height="200"
      :auto-scroll="false"
      :other-raw="otherRaw"
      :selected-arry.sync="tableSelected"
      :table-row-class-name="tableRowClassName"
      @selection-change="selectionChangeHandle"
      @data-change="tableDataChange"
    >
      <el-table-column slot="before" type="selection" reserve-selection width="50" />
    </table-box>
    <div class="qup-title-box"><span class="border" /><span>已选择的施工单位</span></div>
    <template>
      <el-table
        :data="selectedRows"
        height="200"
        style="width: 100%"
      >
        <el-table-column fixed="left" label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click.native.prevent="delSelectedRow(scope.row)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="unitCode" label="施工单位编码" width="180" />
        <el-table-column prop="unitName" label="施工单位名称" width="180" />
        <el-table-column prop="principal" label="负责人" width="180" />
        <el-table-column prop="principalPhone" label="负责人电话" width="180" />
        <el-table-column prop="delegateDesc" label="委派描述" min-width="100">
          <template slot-scope="scope">
            <el-input v-model="scope.row.delegateDesc" type="textarea" class="tool-inp" size="mini" placeholder="请输入委派说明" @input="inputValue" />
          </template>
        </el-table-column>
      </el-table>
    </template>
    <div class="btn-container">
      <c-button @click="cancelHandle">取消</c-button>
      <c-button type="primary" @click="confirmHandle">提交</c-button>
    </div>

  </div>
</template>
<script>
import { getDetailBatch, postBatchCreateUnit, getGetOneByid } from '@/api/decorate'

export default {
  name: 'Units',
  data() {
    return {
      detail: {},
      maxBatch: {},
      otherRaw: {},
      selectedRows: [],
      allTableData: [],
      cancelSelectedRows: [],
      searchConfig: [{ label: '施工单位名称', prop: 'unitName', type: 'text', value: '' }],
      otherFilters: [{ 'id': 'cooperationState', 'property': 'cooperationState', 'operator': '=', 'value': 'B' }],
      tableSelected: [],
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/shopDecoration/pageUnitPupSelect`,
        buttonGroupCode: 'default',
        hideFuncBar: true,
        tabIndex: 0,
        pageSize: 20,
        // 表格字段动态配置
        setting: [
          {
            prop: 'unitCode',
            label: '施工单位编码',
            minWidth: 120
          },
          {
            prop: 'unitName',
            label: '施工单位名称',
            minWidth: 150,
            className: 'btn-green',
            isButton: true,
            clickFun: this.toDetail
          },
          {
            prop: 'principal',
            label: '负责人',
            width: 90,
            hide: true
          },
          {
            prop: 'principalPhone',
            label: '负责人电话',
            width: 120,
            hide: true
          },
          {
            prop: 'buildAmount',
            label: '在建数量',
            width: 110,
            hide: true
          }, {
            prop: 'buildArea',
            label: '在建面积',
            width: 110,
            hide: true
          }, {
            prop: 'talkAmount',
            label: '在谈数量',
            width: 110,
            hide: true
          },
          {
            prop: 'talkArea',
            label: '在谈面积',
            width: 110,
            hide: true
          },
          {
            prop: '',
            label: '预警提示',
            width: 130,
            render: function(createElement, rows) {
              let isMaxArea = false
              let isMaxAmount = false
              if (rows.sameTimeMaxArea < (rows.talkArea || 0) + (rows.buildArea || 0)) isMaxArea = true
              if (rows.sameTimeMaxProject < (rows.talkAmount || 0) + (rows.buildAmount || 0)) isMaxAmount = true
              if (isMaxArea && isMaxAmount) return (<div class='warning-text'>已超过最大承接数量和面积</div>)
              if (isMaxArea && !isMaxAmount) return (<div class='warning-text'>已超过最大承接面积</div>)
              if (!isMaxArea && isMaxAmount) return (<div class='warning-text'>已超过最大承接数量</div>)
              if (!isMaxArea && !isMaxAmount) return ''
            }
          },
          {
            prop: 'assessSumScore',
            label: '评估总分',
            width: 110,
            operator: '=',
            hide: true
          },
          {
            prop: 'currentWarrantyNumber',
            label: '保证金总金额',
            width: 130,
            operator: '=',
            hide: true
          },
          {
            prop: 'sameTimeMaxProject',
            label: '在建项目数量',
            width: 130,
            operator: '=',
            hide: true
          }
        ]
      },
      initSelecteds: []
    }
  },
  computed: {

  },
  watch: {
    allTableData: {
      handler(val, oldVal) {
        this.$nextTick(() => {
          this.reSetTableSelection()
        })
      },
      deep: true
    }
  },
  created() {
    getGetOneByid(this.$route.query.id).then(res => {
      this.detail = res.data
      this.openHandle()
      this.otherRaw = { officeCode: this.detail.officeCode, shopCode: this.detail.shopCode }
      this.$nextTick(() => {
        this.$refs.refTable.initTableData()
      })
    })
  },
  methods: {
    handlerOrg(data) {
      if (!data) return ''
      return data.map(row => row.orgName)
    },
    // 返回列表页
    cancelHandle() {
      this.$store.dispatch('views/goBack')
    },
    confirmHandle() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择施工单位！')
        return
      }
      return postBatchCreateUnit(this.handlerData()).then(res => {
        if (res.success === 1) {
          this.$message.success('操作成功！')
        }
        this.cancelHandle()
      })
    },
    handlerData() {
      const data = []
      for (const item of this.selectedRows) {
        const delegateBatch = this.maxBatch[this.detail.decorationTaskCode]
        data.push({
          delegateDesc: item.delegateDesc,
          constCode: this.detail.constCode, // 门店建设号
          constUnitCode: item.unitCode, // 委派施工单位编号
          decorationTaskCode: this.detail.decorationTaskCode, // 装修任务编号
          unitName: item.unitName, // 委派施工单位名称
          delegateBatch: delegateBatch === undefined ? 1 : delegateBatch + 1
        })
      }
      return data
    },
    inputValue(data) {

    },
    // 清空搜索条件
    clearSearch(data) {
      this.otherFilters = [{ 'id': 'cooperationState', 'property': 'cooperationState', 'operator': '=', 'value': 'B' }]
      this.$nextTick(() => { this.$refs.refTable.initTableData() })
    },
    // 获取搜索条件
    handleSearch(data) {
      this.otherRaw = {}
      this.otherFilters = [...data.filtersRaw, ...[{ 'id': 'cooperationState', 'property': 'cooperationState', 'operator': '=', 'value': 'B' }]]
      this.$nextTick(() => {
        this.$refs.refTable.initTableData()
      })
    },
    toDetail(row) {
      this.$store.dispatch('views/goPage', { path: '/constructionUnitMng/unitManagement', query: { target: 'detail', id: row.id, time: new Date().getTime() }})
    },
    openHandle() {
      const d = [this.detail.decorationTaskCode]
      getDetailBatch(d).then(res => {
        this.maxBatch = {}
        for (const item of res.data || []) {
          if (this.maxBatch[item.decorationTaskCode] === undefined) {
            this.maxBatch[item.decorationTaskCode] = item.delegateBatch
          } else if (this.maxBatch[item.decorationTaskCode] < item.delegateBatch) {
            this.maxBatch[item.decorationTaskCode] = item.delegateBatch
          }
        }
      })
    },
    selectionChangeHandle(rows) {
      this.selectedRows = rows
    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      const filterArr = this.selectedRows.filter(item => item.id === row.id)
      return filterArr.length > 0 ? 'selected-highlight' : ''
    },
    tableDataChange(res) {
      this.allTableData = (res && res.data && res.data.records) || []
      if (this.initSelecteds.length === 0) return
      this.allTableData.forEach((row, keyIndex) => {
        const index = this.initSelecteds.findIndex(v => v.id === row.id)
        if (index > -1) {
          const newRow = { ...row, ...{ keyIndex }}
          const rowIndex = this.selectedRows.findIndex(v => v.id === row.id)
          if (rowIndex === -1) {
            this.selectedRows.push(newRow)
            this.$refs.refTable.toggleRowSelection(newRow, true)
          } else {
            this.$set(this.selectedRows, rowIndex, newRow)
          }
        }
      })
    },
    // 重置当前页已选中数据的复选状态
    reSetTableSelection() {
      // 判断当前表数据中是存在已取消选中的数据，若存在，则取消表格数据的选中
      const delIds = []
      this.cancelSelectedRows.forEach(row => {
        const tmp = this.allTableData.filter(item => item.id === row.id)
        if (tmp.length > 0) { // 在当前页表格数据中则取消选中
          this.$refs.refTable.toggleRowSelection(tmp[0], false)
          delIds.push(row.id)
        }
      })
      delIds.forEach(id => {
        const index = this.cancelSelectedRows.findIndex(row => row.id === id)
        this.cancelSelectedRows.splice(index, 1)

        if (this.initSelecteds && this.initSelecteds.length) {
          const indexSelect = this.initSelecteds.findIndex(row => row.id === id)
          if (indexSelect > -1) {
            this.initSelecteds.splice(indexSelect, 1)
          }
        }
      })
    },
    // 移除已选择方案
    delSelectedRow(row) {
      const tmp = this.allTableData.filter(item => row.id === item.id)
      if (tmp.length > 0) { // 在当前页表格数据中则取消选中
        this.$refs.refTable.toggleRowSelection(tmp[0], false)
      } else { // 未在当前表格数据中，则加入到取消选中的数据集中，并从已选组织表中删除
        this.cancelSelectedRows.push(row)
        const index = this.selectedRows.indexOf(row)
        this.selectedRows.splice(index, 1)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
  .btn-container{
    width: 300px;
    margin: auto;
}
.warning-text{
  color: #F56C6C;
}
/deep/.el-checkbox__inner{
   border: 2px solid #3dc094;
 }
</style>
